package cn.edu.scau.cmi.limingben.composite.Controller;

import java.awt.event.ActionEvent;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import cn.edu.scau.cmi.limingben.composite.model.Consistent_model.*;
import javafx.fxml.Initializable;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;

public class Consistent_Controller implements Initializable {
    @FXML
    private VBox vbox;
    @FXML
    private TreeView<AbstractOrganization> treeView;

    @FXML
    private TextField personName;
    @FXML
    private TextField orgnName;


    @FXML
    public void addPerson(){
        TreeItem<AbstractOrganization> treeItem = getSelectOrgnItem();
        Organization orgn = (Organization) treeItem.getValue();
        Person person = new Person(orgn, personName.getText());
        orgn.addChild(person);
        treeItem.getChildren().add(new TreeItem<AbstractOrganization>(person));
    }
    private TreeItem<AbstractOrganization> getSelectOrgnItem(){
        TreeItem<AbstractOrganization> treeItem = treeView.getRoot();
        if(!treeView.getSelectionModel().isEmpty()){
            if(treeView.getSelectionModel().getSelectedItem().getValue() instanceof Organization){
                treeItem = treeView.getSelectionModel().getSelectedItem();
            }
        }
        return treeItem;
    }
    @FXML
    public void addOrganization(){
        TreeItem<AbstractOrganization> treeItem = getSelectOrgnItem();
        Organization orgn = (Organization) treeItem.getValue();
        Organization organization = new Organization(orgn, orgnName.getText());
        orgn.addChild(organization);
        treeItem.getChildren().add(new TreeItem<AbstractOrganization>(organization));
    }
    private TreeItem<AbstractOrganization> getSelectItem(){
        TreeItem<AbstractOrganization> treeItem = treeView.getRoot();
        if(!treeView.getSelectionModel().isEmpty()){
            treeItem = treeView.getSelectionModel().getSelectedItem();
        }
        return treeItem;
    }
    @FXML
    public void delete(){
        TreeItem<AbstractOrganization> treeItem = getSelectItem();
        if(treeItem.getParent() != null){
            treeItem.getParent().getChildren().remove(treeItem);
            if(treeItem.getParent().getValue() instanceof Organization){
                ((Organization)treeItem.getParent().getValue()).removeChild(treeItem.getValue());
            }
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        TreeItem<AbstractOrganization> root = new TreeItem<AbstractOrganization>(new Organization(null, "初始大组"));
        treeView.setRoot(root);
    }
}
